package com.yunchuang.controller.user;

import com.yunchuang.common.BaseResult;
import com.yunchuang.model.dto.UserUpdateDto;
import com.yunchuang.model.dto.UserUploadAvatarDto;
import com.yunchuang.model.pojo.User;
import com.yunchuang.service.UserService;
import com.yunchuang.service.impl.UserServiceImpl;
import com.yunchuang.utils.JSONUtils;
import com.yunchuang.utils.ProfileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;
import java.util.Collection;

import static com.yunchuang.constant.CommonConstant.SUCCESS_CODE;

/**
 * 下载头像
 *
 * @author ItJiange
 * @date 2023/10/26
 */
@WebServlet("/user/uploadAvatar")
@MultipartConfig
public class UserUploadAvatarController extends HttpServlet {
    private final Logger logger = LoggerFactory.getLogger("logback");

    private UserService userService = new UserServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Part fileObject = req.getPart("file");
        // 文件上传时候的名称
        String fileName = fileObject.getSubmittedFileName();
        String uploadPath = ProfileUtils.getServerOtherContext() + File.separator + fileName;
        File file = new File(uploadPath);
        // 判断上传的父级目录是否存在
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        try {
            // 将文件写到指定文件中
            fileObject.write(uploadPath);
            logger.info(fileName + "上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("保存失败");
        }

        // 在 getSession 中获取 User
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");

        UserUploadAvatarDto userUploadAvatarDto = new UserUploadAvatarDto();
        userUploadAvatarDto.setId(user.getId());
        userUploadAvatarDto.setAvatarUrl(uploadPath);

        BaseResult baseResult = userService.userUpdateAvatar(userUploadAvatarDto);
    }
}
